package com.example.licencecreate.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

/**
 * 获取私钥工具类
 */
@Component
public class KeyTools {

    
    //private static final String BASE_FILE_PATH = "D:\\a_myFile\\dinglian\\other\\licence";
    //private static final String BASE_FILE_PATH = "/opt/licence/";

    //私钥存放路径
    //public static final String PRIVATE_KEY_FILE_PATH = BASE_FILE_PATH + "\\privateKey.keystore";
    //public static final String PRIVATE_KEY_FILE_PATH = BASE_FILE_PATH + "/privateKey.keystore";

    @Value(value = "${key.privatePath}")
    private String privateKeyPath;
    
    //私钥别名
    @Value(value = "${key.privateAlias}")
    public  String privateAlias;
    
    @Value(value = "${key.keyStorePassword}")
    private String keyStorePassword;
    
    @Value(value = "${key.keyPassword}")
    private String keyPassword;

    //获取keystore所需的密码
    //public static final String KEYSTORE_PASSWORD = "dinglian@123";
    //获取私钥所需密码
    //public static final String KEY_PASSWORD = "dinglian$123";

    /**
     * 通过keystore获取private key
     */
    public PrivateKey getPrivateKey() {

        FileInputStream is = null;
        PrivateKey privateKey = null;
        try {
            KeyStore keyStore = KeyStore.getInstance("JKS");
            is = new FileInputStream(privateKeyPath);
            keyStore.load(is, keyStorePassword.toCharArray());
            privateKey = (PrivateKey) keyStore.getKey(privateAlias, keyPassword.toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return privateKey;
    }
}


